package redis

import (
	"fmt"

	redis "go-papers/pkg/gredis"

	"go-papers/tools/config"
)

// Global redis manager
var (
	RedisMgr  *redis.Manager
	mgrconfig = redis.ManagerConfig{}
)

func convertToConfig(c config.Redis) *redis.Config {
	ret := &redis.Config{}
	fn := func(s float64) int {
		return int(s * 1000)
	}
	ret.Addr = c.Addr
	ret.Passwd = c.Pwd
	ret.DB = int(c.Db)
	ret.DialTimeout = fn(c.DialTimeout)
	ret.ReadTimeout = fn(c.ReadTimeout)
	ret.WriteTimeout = fn(c.WriteTimeout)
	ret.PoolSize = int(c.PoolSize)
	ret.MinIdleConns = int(c.MinIdleConns)
	ret.MaxRetries = int(c.MaxRetries)
	return ret
}

func Init() {
	for _, v := range config.GConfig.Redis {
		c := convertToConfig(v)
		mgrconfig[v.Name] = c
	}
	RedisMgr = redis.NewManager(&mgrconfig)
}

func New(schema string) *Client {
	client, err := RedisMgr.NewClient(schema)
	if err != nil {
		if err == redis.ErrNotFoundConfig {
			panic(fmt.Errorf("redis no such config section: %s", schema))
		}
		panic(fmt.Errorf("new redis client error: %s", err.Error()))
	}

	addr := mgrconfig[schema].Addr
	db := mgrconfig[schema].DB

	fmt.Println("redis", schema, addr, db)
	return &Client{client, schema, addr, db}
}
